package ru.ifmo.croak.impl.replication.team1.io;


import ru.ifmo.croak.api.Message;

import java.io.*;
import java.util.UUID;

public class MessageInputStream implements Closeable {
    public static final int BUFFER_SIZE = 1024 * 1024;
    private final ObjectInputStream objectInputStream;

    public MessageInputStream(InputStream inputStream) throws IOException {
        objectInputStream = new ObjectInputStream(new BufferedInputStream(inputStream, BUFFER_SIZE));
    }

    public int nextInt() throws IOException {
        return objectInputStream.readInt();
    }

    public boolean nextBoolean() throws IOException {
        return objectInputStream.readBoolean();
    }

    public Message nextMessage() throws IOException {
        Message message = new Message();
        try {
            message.setId((UUID) objectInputStream.readObject());
        } catch (ClassNotFoundException e) {
            throw new BrokenMessageException(e);
        }
        message.setTime(objectInputStream.readLong());
        message.setAuthor(objectInputStream.readUTF());
        message.setText(objectInputStream.readUTF());
        return message;

    }

    public UUID nextUUID() throws IOException {
        try {
            return (UUID) objectInputStream.readObject();
        } catch (ClassNotFoundException e) {
            throw new BrokenMessageException(e);
        }
    }

    public void close() throws IOException {
        objectInputStream.close();
    }
}
